<template>
  <div class="app-container">
    <!-- 左侧分支面板 -->
    <BranchNavigationPanel
      :branches="branches"
      :current-node="currentNode"
      @branch-switched="handleBranchSwitch"
    />

    <!-- 右侧主内容区域 -->
    <div class="main-content">
      <!-- 标题栏 -->
      <header class="app-header">
        <h1>{{ appName }}</h1>
        <div class="status-indicator">
          <span :class="statusClass">{{ statusText }}</span>
        </div>
      </header>

      <!-- 聊天显示区域 -->
      <div class="chat-area">
        <ChatDisplay
          :messages="currentConversation"
          @create-branch="handleCreateBranch"
        />
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <textarea
          v-model="newMessage"
          placeholder="请输入您的问题..."
          class="message-input"
          @keydown.ctrl.enter="sendMessage"
        ></textarea>
        <div class="upload-area">
          <input
            type="file"
            ref="fileInput"
            accept="image/*"
            class="file-input"
            @change="handleFileUpload"
            multiple
          />
          <button class="upload-button" @click="triggerFileUpload">
            📎 上传图片
          </button>
        </div>
        <button 
          class="send-button"
          @click="sendMessage"
          :disabled="!hasContentToSend"
        >
          发送 (Ctrl+Enter)
        </button>
      </div>
      
      <!-- 图片预览区域 -->
      <div v-if="uploadedFiles.length > 0" class="preview-area">
        <h4>已上传图片:</h4>
        <div class="preview-container">
          <div v-for="(file, index) in uploadedFiles" :key="index" class="preview-item">
            <img :src="file.url" :alt="file.name" class="preview-image" />
            <button class="remove-image" @click="removeImage(index)">×</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import BranchNavigationPanel from './components/BranchNavigationPanel.vue';
import ChatDisplay from './components/ChatDisplay.vue';
import { conversationManager } from './services/conversationService';
import { getAIResponse, checkApiAvailability } from './services/aiService';

export default {
  name: 'App',
  components: {
    BranchNavigationPanel,
    ChatDisplay
  },
  setup() {
    // 状态管理
    const appName = 'AI Message';
    const newMessage = ref('');
    const statusText = ref('准备就绪');
    const statusClass = ref('status-ready');
    const uploadedFiles = ref([]);  // 存储上传的文件
    
    // 用于触发分支列表UI更新的标记
    const refreshFlag = ref(0);

    // 计算属性
    const branches = computed(() => {
      // 通过refreshFlag触发重新计算
      refreshFlag.value;
      
      const managerBranches = conversationManager.getAllBranches();
      // 转换分支对象格式，使用currentNodeId获取实际的节点对象
      return managerBranches.map(branch => ({
        ...branch,
        currentNode: branch.currentNodeId ? conversationManager.getNodeById(branch.currentNodeId) : null
      }));
    });

    // 判断是否有内容可以发送（文本或图片）
    const hasContentToSend = computed(() => {
      return newMessage.value.trim() !== '' || uploadedFiles.value.length > 0;
    });

    const currentNode = computed(() => conversationManager.currentNode);

    // 创建一个响应式的消息数组
    const conversationMessages = ref([]);
    
    // 定义一个函数来更新消息数组
    const updateMessages = () => {
      if (conversationManager && conversationManager.currentPath) {
        const messages = conversationManager.currentPath.map(node => ({
          id: node.id,
          message: node.message,
          role: node.role,
          timestamp: node.timestamp,
          files: node.files || []  // 确保文件信息被正确传递
        }));
        console.log('更新后的对话消息:', messages);
        console.log('更新后的路径节点数量:', conversationManager.currentPath.length);
        conversationMessages.value = messages;
      }
    };
    
    // 初始更新一次消息
    updateMessages();
    
    // 计算属性返回响应式的消息数组
    const currentConversation = computed(() => conversationMessages.value);

    // 方法
    const triggerFileUpload = () => {
      // 触发文件选择对话框
      document.querySelector('.file-input').click();
    };

    const handleFileUpload = (event) => {
      const files = event.target.files;
      if (!files.length) return;

      // 处理选择的文件
      Array.from(files).forEach(file => {
        // 只处理图片文件
        if (file.type.startsWith('image/')) {
          const reader = new FileReader();
          reader.onload = (e) => {
            uploadedFiles.value.push({
              name: file.name,
              type: file.type,
              url: e.target.result,
              file: file
            });
          };
          reader.readAsDataURL(file);
        }
      });

      // 清空文件输入，以便可以重复选择相同的文件
      event.target.value = '';
    };

    const removeImage = (index) => {
      uploadedFiles.value.splice(index, 1);
    };

    const sendMessage = async () => {
      const messageText = newMessage.value.trim();
      
      // 检查是否有内容可以发送
      if (!hasContentToSend.value) return;

      // 准备要发送的文件信息
      const filesToSend = uploadedFiles.value.map(file => ({
        name: file.name,
        type: file.type,
        url: file.url
      }));

      // 清空输入框和上传的文件
      newMessage.value = '';
      uploadedFiles.value = [];

      // 添加用户消息
      statusText.value = '正在发送...';
      statusClass.value = 'status-sending';

      try {
        conversationManager.addMessage(messageText, 'user', filesToSend);
        // 更新消息显示
        updateMessages();

        // 获取当前对话上下文
        const context = conversationManager.getCurrentContext().slice(0, -1); // 不包含刚刚添加的用户消息

        // 调用LM Studio API获取AI回复
        statusText.value = 'AI正在回复...';
        statusClass.value = 'status-thinking';
        console.log('调用AI API前的上下文:', context);
        console.log('调用AI API时传递的文件数量:', filesToSend.length);

        const aiResponse = await getAIResponse(messageText, context, filesToSend);
        console.log('AI回复内容:', aiResponse);
        const assistantNode = conversationManager.addMessage(aiResponse, 'assistant');
        console.log('添加AI回复后的当前节点:', assistantNode);
        console.log('添加AI回复后的路径长度:', conversationManager.currentPath.length);
        // 更新消息显示
        updateMessages();

        statusText.value = '准备就绪';
        statusClass.value = 'status-ready';
      } catch (error) {
        statusText.value = '发送失败';
        statusClass.value = 'status-error';
        console.error('发送消息失败:', error);
        // 在聊天记录中添加错误消息，方便用户了解情况
        conversationManager.addMessage(`抱歉，无法获取AI回复: ${error.message}。请确保LM Studio服务已启动并正常运行。`, 'system');
        // 更新消息显示
        updateMessages();
      }
    };

    const handleCreateBranch = (messageId) => {
      try {
        conversationManager.createBranch(messageId);
        statusText.value = '分支创建成功';
        statusClass.value = 'status-success';
        
        // 更新refreshFlag来强制重新计算branches，确保UI刷新
        refreshFlag.value++;
        
        // 更新对话视图，显示新分支的对话内容
        updateMessages();
        
        // 3秒后恢复状态
        setTimeout(() => {
          statusText.value = '准备就绪';
          statusClass.value = 'status-ready';
        }, 3000);
      } catch (error) {
        statusText.value = '创建分支失败';
        statusClass.value = 'status-error';
        console.error('创建分支失败:', error);
      }
    };

    const handleBranchSwitch = (branchId) => {
      try {
        conversationManager.switchBranch(branchId);
        statusText.value = '已切换分支';
        statusClass.value = 'status-success';
        
        // 更新refreshFlag来强制重新计算branches，确保UI刷新
        refreshFlag.value++;
        
        // 更新对话视图，显示切换后的分支对话内容
        updateMessages();
        
        // 3秒后恢复状态
        setTimeout(() => {
          statusText.value = '准备就绪';
          statusClass.value = 'status-ready';
        }, 3000);
      } catch (error) {
        statusText.value = '切换分支失败';
        statusClass.value = 'status-error';
        console.error('切换分支失败:', error);
      }
    };

    // 初始化
    onMounted(async () => {
      console.log('应用已启动');
      console.log('当前对话路径:', conversationManager.currentPath);
      console.log('当前节点:', conversationManager.currentNode);
      console.log('所有分支:', conversationManager.getAllBranches());
      console.log('当前对话消息:', currentConversation.value);
      
      // 检查LM Studio API可用性
      try {
        statusText.value = '正在检查LM Studio服务...';
        statusClass.value = 'status-sending';
        
        const isAvailable = await checkApiAvailability();
        
        if (isAvailable) {
          statusText.value = 'LM Studio服务已连接';
          statusClass.value = 'status-success';
          setTimeout(() => {
            statusText.value = '准备就绪';
            statusClass.value = 'status-ready';
          }, 2000);
        } else {
          statusText.value = 'LM Studio服务未连接';
          statusClass.value = 'status-error';
          console.warn('警告: LM Studio服务未连接，请确保LM Studio已启动。');
          conversationManager.addMessage('警告: LM Studio服务未连接，请确保LM Studio已启动并在默认端口(1234)上运行。', 'system');
        }
      } catch (error) {
        statusText.value = '检查LM Studio服务失败';
        statusClass.value = 'status-error';
        console.error('检查LM Studio服务时出错:', error);
        conversationManager.addMessage(`检查LM Studio服务时出错: ${error.message}`, 'system');
      }
      
      // 如果没有任何消息，手动添加一些初始消息
      console.log('应用挂载时的当前路径长度:', conversationManager.currentPath.length);
      console.log('应用挂载时的当前节点:', conversationManager.currentNode);
      console.log('应用挂载时的根节点:', conversationManager.root);
      if (conversationManager.currentPath.length === 0) {
        console.log('手动添加初始消息...');
        try {
          conversationManager.addMessage('1+1=?', 'user');
          conversationManager.addMessage('2', 'assistant');
          conversationManager.addMessage('再乘以14', 'user');
          conversationManager.addMessage('28', 'assistant');
          // 添加一个带图片的示例消息
          const mockImage = {
            name: 'example.png',
            type: 'image/png',
            url: ''
          };
          conversationManager.addMessage('这是一张示例图片', 'user', [mockImage]);
        } catch (error) {
          console.error('添加初始消息失败:', error);
        }
      }
    });

    return {
      appName,
      newMessage,
      statusText,
      statusClass,
      branches,
      currentNode,
      currentConversation,
      uploadedFiles,
      hasContentToSend,
      sendMessage,
      handleCreateBranch,
      handleBranchSwitch,
      triggerFileUpload,
      handleFileUpload,
      removeImage
    };
  }
};
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-bottom: 1px solid #dcdcdc;
}

.app-header h1 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.status-indicator {
  font-size: 14px;
}

.status-ready {
  color: green;
}

.status-sending {
  color: blue;
}

.status-thinking {
  color: purple;
}

.status-success {
  color: green;
}

.status-error {
  color: red;
}

.chat-area {
  flex: 1;
  overflow: hidden;
  display: flex;
}

.input-area {
  display: flex;
  gap: 10px;
  padding: 20px;
  background-color: white;
  border-top: 1px solid #dcdcdc;
}

.message-input {
  flex: 1;
  min-height: 60px;
  max-height: 120px;
  padding: 10px;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
  font-family: inherit;
}

.message-input:focus {
  outline: none;
  border-color: #0066cc;
}

.send-button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
  transition: background-color 0.2s;
}

.send-button:hover:not(:disabled) {
  background-color: #45a049;
}

.send-button:disabled {
      background-color: #cccccc;
      cursor: not-allowed;
    }

    /* 文件上传区域样式 */
    .upload-area {
      display: flex;
      align-items: center;
      margin-right: 10px;
    }

    .file-input {
      display: none;
    }

    .upload-button {
      padding: 8px 16px;
      background-color: #0066cc;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      white-space: nowrap;
      transition: background-color 0.2s;
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .upload-button:hover {
      background-color: #0052a3;
    }

    /* 图片预览区域样式 */
    .preview-area {
      padding: 10px 20px;
      background-color: #f9f9f9;
      border-top: 1px solid #e0e0e0;
    }

    .preview-area h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #333;
    }

    .preview-container {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    .preview-item {
      position: relative;
      width: 100px;
      height: 100px;
      border: 1px solid #ddd;
      border-radius: 4px;
      overflow: hidden;
      background-color: white;
    }

    .preview-item img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .remove-image {
      position: absolute;
      top: 5px;
      right: 5px;
      width: 20px;
      height: 20px;
      background-color: rgba(255, 0, 0, 0.7);
      color: white;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      line-height: 1;
    }

    .remove-image:hover {
      background-color: rgba(255, 0, 0, 1);
    }
  </style>
